<template>
  <view class='QuestionDetail-container'>
    <!--    - {{ type }} - {{ index }} - {{ item.id }}-->
    <scroll-view scroll-y="true" style="height: 100%" v-if="dataStatus === 'result'">
      <view class="question-container">
        <!--      {{ index }}.{{ question.id }} {{ question.title }}-->
        <view style="margin-bottom: 60rpx;">
          <span class="question">
            <text class="tag">{{ question.typeStr }}</text>
            <!--            <text class="tag">{{ question.kemu }}</text>-->
            <text v-if="easyError" class="tag" style="background-color: #10D0B1">易错题</text>
            <text v-if="local" class="tag" style="background-color: #10D0B1">地方题</text>
            <text v-if="carType" class="tag" style="background-color: #10D0B1">{{ carType }}</text>
            <text
                :style="{'line-height': '2em', 'font-size': (34 + questionSetting.fontSize)+'rpx'}">{{ question.title }}
            </text>
            <VoicePlayer v-if="openYuyin" class="item" :questionId="question.id" :storeId="storeId" :index="index"
                         :mode="mode"
                         :vip="kemuVIP"></VoicePlayer>
          </span>
          <ZImage style="width: 690rpx;height: 300rpx;margin-top: 30rpx;position: relative" v-if="img" :img="img"
                  @click="toPreview([img], img)"></ZImage>
        </view>
        <template v-for="n in [1,2,3,4]">
          <view :class="['option-container', getOptionStyle(n)]" @click="selectOption(n)" :key="n"
                v-if="question['option'+n]">
            <view :class="['option-label']">{{ answerLabel[n] }}</view>
            <text class="f1" :style="{'font-size': (34 + questionSetting.fontSize)+'rpx'}">{{
                question['option' + n]
              }}
            </text>
          </view>
        </template>
        <view v-if="!question.status && mode !== 'recite' && question.type === 2" class="submit-btn"
              @click="submitAnswer">确认答案
        </view>
        <view class="answer-option" v-if="showAnswer" :style="{'font-size': (30 + questionSetting.fontSize)+'rpx'}">
          <text>正确答案：</text>
          <text style="color: #3073F6;">{{ question.answerStr }}</text>
          <template v-if="question.result.length">
            <text style="margin-left: 60rpx;">你的选择：</text>
            <text style="color: #FB3C3D;">
              {{ answerFormat(question.result) }}
            </text>
          </template>
        </view>
      </view>
      <!--      <view class="process-container">-->
      <!--        <VoicePlayer v-if="openYuyin" class="item" :questionId="question.id" :index="index" :mode="mode"-->
      <!--                     :vip="kemuVIP"></VoicePlayer>-->
      <!--        <view class="item status-collection" @click="errorCorrection">-->
      <!--          <image src="@/static/jiucuo.png"-->
      <!--                 style="width: 42rpx; height: 40rpx;margin-bottom: 10rpx;"></image>-->
      <!--          <text class="collectionColor">纠错</text>-->
      <!--        </view>-->

      <!--        <view class="item status-collection" @click="collect">-->
      <!--          <image v-if="question.collect" src="@/static/collection_select.png"-->
      <!--                 style="width: 42rpx; height: 40rpx;;margin-bottom: 10rpx;"></image>-->
      <!--          <image v-else src="@/static/collection@2x.png"-->
      <!--                 style="width: 42rpx; height: 40rpx; margin-bottom: 10rpx;"></image>-->
      <!--          <text :class="['collectionColor',question.collect ? 'collectionColorSelect' :'']">-->
      <!--            {{ question.collect ? '已收藏' : '收藏' }}-->
      <!--          </text>-->
      <!--        </view>-->

      <!--        <view v-if="type === 'wrong'" class="item status-collection" @click="onRemove">-->
      <!--          <image src="@/static/yichucuoti@2x.png"-->
      <!--                 style="width: 44rpx; height: 42rpx; margin-bottom: 10rpx;"></image>-->
      <!--          <text class="collectionColor">-->
      <!--            移出错题-->
      <!--          </text>-->
      <!--        </view>-->
      <!--      </view>-->
      <!-- <view style="height: 50rpx;background-color: green" @click="_testClick"></view> -->
      <!--      <VideoLessonView :showPeople="true" :title="question.tags[0].title+' 视频精讲'" v-if="question.videos && question.videos.length"-->
      <!--                       btnText="看视频"-->
      <!--                       tips1="老师教你窍门"-->
      <!--                       tips2="快速做题"-->
      <!--                       @videoClick="onVideoClick"-->
      <!--                       :questionId="question.id" :videos="question.videos"></VideoLessonView>-->
      <view class="answer-container" v-if="showAnswer">
        <view class="label-container" v-if="question.skills.length">
          <view class="icon"></view>
          <view class="label">试题详解</view>
          <view class="right icon"></view>
        </view>
        <view v-for="(skill, i) in question.skills" :key="skill.id" class="skill-container">
          <view class="label">
            <view class="divider"></view>
            答题技巧{{ question.skills.length > 1 ? '（' + (i + 1) + '）' : '' }}
          </view>
          <view class="content" :style="{'font-size': (30 + questionSetting.fontSize)+'rpx'}">
            {{ skill.title }}
          </view>
          <view class="hide-skill" v-if="!canOpenAnswer">
            <view class="btn" @click="goVip">查看完整技巧</view>
          </view>
          <image class="img" :src="skill.imgUrl" mode="widthFix" @click="toPreviewSkill(skill.imgUrl)"
                 v-if="skill.imgUrl"></image>
        </view>
        <view class="label-container" v-if="question.law">
          <view class="icon"></view>
          <view class="label">相关交通法规</view>
          <view class="right icon"></view>
        </view>
        <view class="content" v-if="question.law " :style="{'font-size': (30 + questionSetting.fontSize)+'rpx'}">
          {{ question.law }}
          <view class="hide-skill" v-if="!canOpenAnswer">
            <view class="btn" @click="goVip">查看完整技巧</view>
          </view>
        </view>
      </view>
      <view style="height: 300rpx"></view>
    </scroll-view>
    <view v-else style="display: flex;justify-content: center;align-items: center;flex-direction:column;height: 80%">
      <template v-if="dataStatus === 'err'">
        <view>请求失败</view>
        <view style="border: 1px solid #ccc;padding: 10rpx 40rpx;margin-top: 20rpx;border-radius: 20rpx"
              @click="retryInit">重试
        </view>
      </template>
      <template v-else-if="dataStatus === 'empty'">
      </template>
      <template v-else-if="dataStatus === 'request'">
        加载中...
      </template>
    </view>
  </view>
</template>

<script>
import questionCache from "@/libs/questionCache";
import VoicePlayer from "@/pages/detail/VoicePlayer";
import ZImage from "@/components/ZImage";
import {mapGetters, mapActions} from 'vuex'
import {courseApi} from "../../api";
import VideoLessonView from "../home/VideoLessonView.vue";

export default {
  name: 'QuestionDetail',
  props: ['task', 'storeId', 'isManfen'],
  components: {
    VideoLessonView,
    VoicePlayer,
    ZImage,
  },
  data() {
    return {
      dataStatus: 'empty',
      imageError: 0,
      question: null,
      type: null,
      index: null,
      item: null,
      img: null,
      result: [],
      mode: 'answer',
      freeOpenAnswer: false,
      answerLabel: [, 'A', 'B', 'C', 'D'],
    }
  },
  options: {
    styleIsolation: "shared"
  },
  computed: {
    ...mapGetters(['appName', 'openYuyin', 'questionSetting', 'isKemu1VIP', 'isKemu2VIP', 'isKemu3VIP', 'isKemu4VIP']),
    ...mapGetters('args', ['freeOpenAnswerCount']),
    kemuVIP() {
      if (this.question) {
        if (this.question.kemu === 1) {
          return this.isKemu1VIP
        }
        if (this.question.kemu === 2) {
          return this.isKemu2VIP
        }
        if (this.question.kemu === 3) {
          return this.isKemu3VIP
        }
        if (this.question.kemu === 4) {
          if (this.isManfen) {
            return this.isKemu1VIP || this.isKemu4VIP
          } else {
            return this.isKemu4VIP
          }
        }
      }
    },
    canOpenAnswer() {
      const vip = this.kemuVIP
      if (vip) {
        return true
      }
      return this.freeOpenAnswer
    },

    showAnswer() {
      return this.mode === 'recite' || (this.question && this.question.status !== 0)
    },
    easyError() {
      if (!this.question) {
        return false
      }

      const {tags} = this.question;
      let isEasy = false;
      if (tags) {
        tags.forEach((item, index) => {
          //易错题
          if (item.id === 10026 || item.id === 10045) {
            isEasy = true;
          }
        })
      }
      return isEasy;
    },
    local() {
      if (!this.question) {
        return false
      }

      if (this.question.cityCode) {
        return true
      }
      return false
    },
    carType() {
      if (!this.question) {
        return null
      }

      if (this.question.carType === 1) {
        return null
      }

      if (this.question.carType === 2) {
        return '货车专题'
      }

      if (this.question.carType === 3) {
        return '客车专题'
      }

      if (this.question.carType === 4) {
        return '摩托专题'
      }
      return null
    },
  },
  created() {
    questionCache.getStore(this.storeId).subscribe('changeMode', (mode) => {
      this.mode = mode
    })
    questionCache.getStore(this.storeId).subscribe('clearAnswer', () => {
      // 等缓存先清理完
      setTimeout(() => {
        this.retryInit()
      }, 300)
    })
    if (this.task) {
      this.setData(this.task.type, this.task.kemu, this.task.item, this.task.index)
    }
  },
  methods: {
    ...mapActions(['answer']),
    ...mapActions('question', ['questionInfo', 'questionAnswer', 'questionCollect', 'questionUncollect']),
    ...mapActions('user', ['getUser']),
    ...mapActions('args', ['deductFreeOpenAnswerCount']),
    setData(type, kemu, item, index) {
      if (this.isChanged(type, kemu, item, index)) {
        console.log('detail changed', type, item.id, index)
        this.init(this.item.id)
      }
    },

    clearData() {
      this.dataStatus = 'empty'
      this.question = null
      this.type = null
      this.index = null
      this.item = null
    },

    isChanged(type, kemu, item, index) {
      let changed = false
      if (this.item && item) {
        if (this.item.id !== item.id) {
          changed = true
        }
      } else {
        if (this.item && !item) {
          changed = true
        } else if (!this.item && item) {
          changed = true
        }
      }

      if (changed) {
        // console.log('item changed')
      }

      if (this.index !== index) {
        // console.log('index changed')
        changed = true
      }

      if (this.type !== type) {
        // console.log('type changed')
        changed = true
      }

      if (this.kemu !== kemu) {
        // console.log('kemu changed')
        changed = true
      }


      if (changed) {
        this.item = item
        this.index = index
        this.type = type
        this.kemu = kemu
      }
      return changed
    },

    async retryInit() {
      console.log('retryInit', this.item)
      if (this.item) {
        uni.showLoading({
          title: '加载中...',
        })
        await this.init(this.item.id)
        uni.hideLoading()
      }
      console.log('retryInit finished')
    },
    async init(id) {
      this.result = []
      this.question = null
      let question = questionCache.getStore(this.storeId).getQuestion(this.index)
      // console.log('getQuestion', question)
      if (!question) {
        try {
          this.dataStatus = 'request'
          question = await this.questionInfo(id)
          const res = await courseApi.contentsByQuestion('QNW000003', id)
          question.videos = res.data.data.list
          questionCache.getStore(this.storeId).setQuestion(this.index, question)
          this.dataStatus = 'result'
        } catch (e) {
          this.dataStatus = 'err'
        }
      } else {
        this.dataStatus = 'result'
      }
      this.freeOpenAnswer = false

      const item = questionCache.getStore(this.storeId).getItem(this.index)
      if (item.status) {
        question.result = item.result.split('')
        question.status = item.status
      } else {
        question.status = 0
      }
      this.imageError = 0
      this.img = question.img || (question.signIcon && question.signIcon.img)
      this.question = question
    },
    async _testClick() {
      this.selectOption(1)
      this.selectOption(2)
    },
    async selectOption(index) {
      if (this.showAnswer) {
        return
      }

      const foundIndex = this.question.result.findIndex(item => item == index)
      if (foundIndex === -1) {
        this.question.result.push(index)
        this.question.result.sort()
      } else {
        this.question.result.splice(foundIndex, 1)
      }

      console.log('selectOption', this.question.result)

      if (this.question.type !== 2) {
        await this.submitAnswer()
      }
    },
    async submitAnswer() {
      if (!this.question.result.length) {
        return
      }

      if (this.question.status) {
        return
      }

      const result = this.question.result.join('')
      const status = this.question.answer === result ? 1 : -1
      console.log('this.question.result', this.question.result)
      this.question.status = status

      try {
        await this.questionAnswer({
          type: this.type,
          id: this.question.id,
          result,
          status,
          index: this.index,
          kemu: this.question.kemu
        })
        this.answer()
        questionCache.getStore(this.storeId).answer({
          id: this.question.id,
          index: this.index,
          status,
          result,
        })
        if (status === 1) {
          uni.showToast({
            icon: 'none',
            title: '回答正确',
            duration: 1000
          })
        } else {
          if (!this.kemuVIP) {
            const success = await this.deductFreeOpenAnswerCount()
            if (success) {
              this.freeOpenAnswer = true
              uni.$emit('showFreeToast', {
                count: this.freeOpenAnswerCount,
                type: 'answer'
              })
            } else {
              questionCache.getStore(this.storeId).publish('unlockVIP', {
                from: 'error',
                question: this.question
              })
              uni.showToast({
                icon: 'none',
                title: '回答错误',
                duration: 1000
              })
            }
          } else {
            uni.showToast({
              icon: 'none',
              title: '回答错误',
              duration: 1000
            })
          }
        }
      } catch (e) {
        console.log(e)
        uni.showToast({
          icon: 'error',
          title: e.data.msg,
          duration: 2000
        })
      }
    },
    onVideoClick() {
      questionCache.getStore(this.storeId).publish('pauseExam')
    },
    toPreviewSkill(current) {
      const arr = []
      this.question.skills.map(skill => {
        if (skill.imgUrl) {
          arr.push(skill.imgUrl)
        }
      })

      this.toPreview(arr, current)
    },
    onImageError() {
      this.imageError += 1
    },
    onImageLoaded(e) {
      console.log(e)
    },
    reloadImage() {
      this.imageError = 0
    },
    toPreview(arr, current) {
      // this.img = 'http://dasdfas.ccaasd'
      uni.previewImage({
        // 需要预览的图片链接列表。若无需预览，可以注释urls
        urls: arr,
        // 为当前显示图片的链接/索引值
        current: current,
        // 图片指示器样式
        indicator: 'default',
        // 是否可循环预览
        loop: true,
        showmenu: false,
      });
    },
    answerFormat(result) {
      let str = ''
      result.map(item => {
        str += String.fromCharCode(64 + parseInt(item))
      })
      return str
    },

    getOptionStyle(index) {
      //未提交
      if (this.question.status === 0) {
        if (this.mode === 'recite') {
          //背题模式，显示正确答案
          if (this.question.answer.indexOf(index + '') > -1) {
            return 'blue'
          }
        } else {
          if (this.question.result.find(item => item == index)) {
            // 显示 我选的
            return 'gray'
          }
        }
      } else {
        if (this.question.answer.indexOf(index + '') === -1) {
          // 错误选项
          if (this.question.result.find(item => item == index)) {
            return 'red 1'
          }
          return ''
        } else {
          // 正确选项

          if (this.question.type === 2) {
            // 多选
            if (this.question.result.find(item => item == index)) {
              // 选对
              return 'blue 1'
            } else {
              // 漏选
              return 'blue_text'
            }
          } else {
            // 单选
            return 'blue 4'
          }
        }
      }

      return ''
    },
    goVip() {
      questionCache.getStore(this.storeId).publish('unlockVIP', {question: this.question})
    }
  }
}
</script>

<style lang='scss'>
.QuestionDetail-container {
  height: 100%;

  ::v-deep .video_less_view {
    width: 710rpx;
    margin: 20rpx;
  }

  .error-tips {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 300rpx;
    color: #999;
    font-size: 16px;
    background-color: #f9f9f9;
  }

  .question-container {
    padding: 20rpx 30rpx 20rpx;
    background-color: #fff;

    .question {
      font-size: 32rpx;

      .tag {
        background-color: #3073f6;
        color: #fff;
        font-size: 22rpx;
        margin-right: 10rpx;
        padding: 6rpx 14rpx;
        border-radius: 10rpx;
        vertical-align: text-top;
        display: inline-block;
      }
    }

    .option-container {
      display: flex;
      margin-top: 40rpx;
      align-items: center;
      font-size: 34rpx;
      line-height: 1.75em;

      &.blue {
        color: #3073f6;

        .option-label {
          background-color: #3073f6;
          color: #fff;
          border: none;
        }
      }

      &.blue_text {
        color: #3073f6;

        .option-label {
          border: 2rpx solid #3073f6;
          color: #3073f6;
        }
      }

      &.gray {
        .option-label {
          background-color: rgba(0, 0, 0, 0.9);
          color: #fff;
          border: 2rpx solid rgba(0, 0, 0, 0.9);
        }
      }

      &.red {
        color: #FB3C3D;

        .option-label {
          background-color: #FB3C3D;
          color: #fff;
          border: none;
        }
      }

      .option-label {
        width: 56rpx;
        height: 56rpx;
        box-sizing: border-box;
        border: 1px solid rgba(0, 0, 0, 0.9);
        border-radius: 28rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        color: rgba(0, 0, 0, 0.9);
        margin-right: 32rpx;
      }
    }
  }

  .answer-option {
    background-color: #F2F4F7;
    font-size: 30rpx;
    font-weight: 500;
    height: 90rpx;
    display: flex;
    align-items: center;
    border-radius: 10rpx;
    padding: 0 36rpx;
    margin-top: 50rpx;
  }

  .submit-btn {
    background-color: #3073f6;
    height: 90rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 50rpx;
    color: #fff;
    font-size: 15px;
    border-radius: 45rpx;
  }

  @keyframes tiao {
    0% {
      height: 90rpx;
      padding: 0 65rpx;
      font-size: 16px;
    }
    50% {
      height: 80rpx;
      padding: 0 60rpx;
      font-size: 14px;
    }
    100% {
      height: 90rpx;
      padding: 0 65rpx;
      font-size: 16px;
    }
  }

  .answer-container {
    padding: 20rpx 30rpx;
    margin-top: 20rpx;
    background-color: #fff;
    position: relative;

    .hide-skill {
      position: absolute;
      top: 0;
      bottom: 0;
      right: 0;
      left: 250rpx;
      background-color: #fff;
      box-shadow: 0px -20px 50px 20px #fffa;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      z-index: 1;

      .btn {
        background-image: linear-gradient(90deg, #f8dcc6, #edc5a3);
        height: 80rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 0 60rpx;
        border-radius: 100rpx;
        font-weight: bold;
        z-index: 5;
        color: #694837;
        animation: tiao 1000ms infinite;
      }
    }

    .label-container {
      display: flex;
      margin-bottom: 24rpx;
      justify-content: center;
      align-items: center;

      .icon {
        width: 39px;
        height: 4px;
        background: linear-gradient(270deg, rgba(48, 115, 246, 0.46) 0%, rgba(48, 115, 246, 0) 100%);
        border-radius: 4px;
        margin: 0 14rpx;

        &.right {
          transform: rotate(180deg);
        }
      }

      .label {
        font-weight: 500;
        font-size: 21px;
        color: #000000;
        line-height: 29px;
      }
    }

    .content {
      font-size: 30rpx;
      color: #3d3d3d;
      margin-bottom: 70rpx;
      line-height: 1.75em;
      white-space: pre-line;
    }

    .skill-container {
      margin-bottom: 70rpx;
      display: flex;
      flex-direction: column;
      position: relative;

      .label {
        .divider {
          width: 6rpx;
          height: 26rpx;
          background: linear-gradient(180deg, #329EF4 0%, #2D96F2 100%);
          border-radius: 2px;
          margin-right: 16rpx;
        }

        font-weight: 500;
        color: #0B0B0B;
        font-size: 34rpx;
        margin-bottom: 20rpx;
        display: flex;
        align-items: center;
      }

      .content {
        font-size: 30rpx;
        color: #3D3D3D;
        margin-bottom: 10rpx;
      }
    }

    .img {
      width: 100%;
    }
  }
}
</style>
